import { mapGetters } from 'vuex';
import Webfs from './utils/webfs';
import { conversionUnit, userBrowser, handleHostname,handleCopy } from './utils/tools';
import Notify from './utils/notify';
import initComponent from './components/templates/index';
// import langMap from "./locale/langmap";
import mitt from 'mitt';

// 挂载全局API
export default function configGlobalAPI(VueInstance) {
    // configI18n(VueInstance);
    baseMixin(VueInstance);
}

function baseMixin(app) {

    app.config.globalProperties.$bus = new mitt();


    // const $bus = new Vue()
    // Vue.prototype.$bus = $bus

    // initComponent(Vue);
    initComponent(app);

    app.mixin({
        // directives,
        methods: {
            async handleWebfs(request, data, options = "download") {
                if (!data || typeof data !== "object") data = {};
                if (!options || typeof options !== "object")
                    options = { executor: options || "download" };
                let executor = options.executor;
                if (typeof request === "function") {
                    options[executor] = true;
                    executor = "request";
                }
                switch (executor) {
                    case "download":
                    case "print":
                        break;
                    default:
                        executor = "request";
                        break;
                }
                Notify();
                const promise = Promise.resolve(
                    Webfs[executor](
                        request,
                        {
                            contextId: global.SYSID,
                            lang: global.LANG,
                            Authorization: global.AUTH_TOKEN,
                            token: global.AUTH_TOKEN,
                            ...data
                        },
                        options
                    )
                );
                return promise
                    .then(res => {
                        return Promise.resolve(res);
                    })
                    .catch(err => {
                        Notify(undefined, err.message);
                        if (err.code == 200) {
                            if (data.showmessage != 'no') {
                                this.$Message.success(err.message);
                            }
                            return Promise.resolve(err);
                        }
                        this.$Message.error(err.message);
                        return Promise.reject(err);
                    });
            },
            handleAuth(auth) {
                return this.getAuthList.indexOf(auth) > -1;
            },
            /**
             *
             * @param {} params=7
             * @description 前几天日期区间
             */
            handleDateRange(params = 7) {
                const now = new Date(),
                    pre = new Date();
                pre.setDate(pre.getDate() - params + 1);
                const zorePrefix = function (val) {
                    return val - 9 > 0 ? val : `0${val}`;
                };
                return [
                    `${pre.getFullYear()}-${zorePrefix(
                        pre.getMonth() + 1
                    )}-${zorePrefix(pre.getDate())}`,
                    `${now.getFullYear()}-${zorePrefix(
                        now.getMonth() + 1
                    )}-${zorePrefix(now.getDate())}`
                ];
            },
            //用于columns 的 render显示
            findRenderLabel(data = [], value, key = "label", isTag = false) {
                var valKey = "value";
                if (Array.isArray(key)) {
                    valKey = key[1] || "value";
                    key = key[0] || "label";
                }
                const result = data.find(function (item, index) {
                    return item && typeof item === "object"
                        ? item[valKey] == value
                        : index == value;
                });
                const isObj = result && typeof result === "object";
                if (isTag && isObj) {
                    return (
                        <Tag
                            color={result.color || result.theme}
                            class="status-tag"
                            type="border"
                        >
                            {result[key]}
                        </Tag>
                    );
                }
                return isObj ? result[key] : result;
            },
            // 单位换算
            handleUnit: conversionUnit,
            //处理浏览器提示
            handleUserBrowser: userBrowser,
            // 数组去重
            arrayUnique(arr, name) {
                var hash = {};
                return arr.reduce((item, next) => {
                    hash[next[name]]
                        ? ""
                        : (hash[next[name]] = true && item.push(next));
                    return item;
                }, []);
            },
            // 根据某个字段进行数组的排序
            compareAttribute(property) {
                return function (a, b) {
                    var value1 = a[property];
                    var value2 = b[property];
                    return value1 - value2;
                }
            },
            // 获取时间指定天数
            getDay(day) {
                var today = new Date();
                var targetday_milliseconds =
                    today.getTime() + 1000 * 60 * 60 * 24 * day;
                today.setTime(targetday_milliseconds); //注意，这行是关键代码
                var tYear = today.getFullYear();
                var tMonth = today.getMonth();
                var tDate = today.getDate();
                tMonth = this.doHandleMonth(tMonth + 1);
                tDate = this.doHandleMonth(tDate);
                return tYear + "-" + tMonth + "-" + tDate;
            },
            doHandleMonth(month) {
                var m = month;
                if (month.toString().length == 1) {
                    m = "0" + month;
                }
                return m;
            },
            // 公共错误提示延迟30秒
            errorMessage(message) {
                this.$Message.error({
                    content: message,
                    duration: 30,
                    closable: true
                });
            },
            //处理多域名问题
            handleHostname,
            // 处理copy,
            handleCopy(target, message = "已复制数据！") {
                if (typeof target === "string")
                    target = document.querySelector(target) || target;
                if (target && handleCopy(target) && message) {
                    this.$Message.success({ content: message, duration: 2 });
                }
            },
            // 跳转文档
            jumpHelp(href) {
                window.open(href);
                event.preventDefault();
            },
        },
        computed: {
            ...mapGetters("layout", ["getAuthList"]),
            //获取环境前缀
            getEnvPrefix() {
                return global.envPrefix;
            }
        }
    });
}